package caiwei.android.service;

import java.io.File;
import java.io.IOException;

import caiwei.android.utilities.Constant;

import android.app.Service;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

/**
 * Service 演示
 * 
 * @author caiwei
 * @date2012-3-14
 * @version 1.0
 */
public class ServiceMyService extends Service
{
	private static final Uri MMUSICURI_URI = Uri.fromFile(new File(
			"/sdcard/sound.mp3"));
	private MediaPlayer mMediaPlayer = null;

	public class MyBinder extends Binder
	{
		public void playMusicForOut()
		{
			ServiceMyService.this.playMusic();
		}
		public void stopMusicForOut()
		{
			ServiceMyService.this.stopCurrentMediaPlayer();
		}
	}
	@Override
	public IBinder onBind(Intent intent)
	{
		Log.i(Constant.TAG, "Service onBind");
		return new MyBinder();
	}

	@Override
	public void onCreate()
	{
		super.onCreate();
		Log.i(Constant.TAG, "service onCreate!");
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId)
	{
		Log.i(Constant.TAG, "service onStart!");
		playMusic();
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void unbindService(ServiceConnection conn)
	{
		super.unbindService(conn);
		Log.i(Constant.TAG, "service unbind!");
		stopCurrentMediaPlayer();
	}

	@Override
	public void onDestroy()
	{
		super.onDestroy();
		Log.i(Constant.TAG, "service onDestroy!");
		stopCurrentMediaPlayer();
	}

	private void playMusic()
	{
		stopCurrentMediaPlayer();
		mMediaPlayer = new MediaPlayer();
		mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
		try
		{
			mMediaPlayer.setDataSource(getApplicationContext(), MMUSICURI_URI);
			mMediaPlayer.prepare();

		} catch (IllegalArgumentException e)
		{
			e.printStackTrace();
		} catch (SecurityException e)
		{
			e.printStackTrace();
		} catch (IllegalStateException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
		mMediaPlayer.start();

	}

	private void stopCurrentMediaPlayer()
	{
		if (mMediaPlayer != null)
		{
			mMediaPlayer.stop();
			mMediaPlayer.release();
			mMediaPlayer = null;
		}
	}
}
